package com.mrx.pvzcommunity.controller;

import com.mrx.pvzcommunity.model.Response;
import com.mrx.pvzcommunity.model.Result;
import com.mrx.pvzcommunity.model.pvz.Env;
import com.mrx.pvzcommunity.model.pvz.Plant;
import com.mrx.pvzcommunity.service.PlantService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@RequiredArgsConstructor
@Api(tags = "植物操作")
@RequestMapping(value = "/plant")
@CrossOrigin(originPatterns = "*", allowCredentials = "true")

public class PlantController {

    private final PlantService plantService;

    @GetMapping("/filter")
    @ApiOperation(value = "查询植物", notes = "根据一定条件查询植物 API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "env", value = "植物出现环境", dataTypeClass = Env.class, example = "day"),
            @ApiImplicitParam(name = "name", value = "植物名字", dataTypeClass = String.class, example = "豌豆射手"),
            @ApiImplicitParam(name = "dp", value = "植物是否为一次性植物", dataTypeClass = Boolean.class, example = "false")
    })

    public Result<List<Plant>> getPlants(
            @RequestParam(required = false) Env env,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Boolean dp
    ) {
        if (env != null && dp != null) {
            return plantService.findPlantByEnvAndDp(env.data, dp);
        } else if (env != null) {
            return plantService.findPlantByEnv(env.data);
        } else if (name != null) {
            return plantService.findPlantByName(name);
        } else if (dp != null) {
            return plantService.findPlantByDisposable(dp);
        }
        return Result.createResult(Response.Code.NEED_ARG, Collections.emptyList());
    }

    @GetMapping("/all")
    @ApiOperation(value = "查询所有植物", notes = "查询所有植物 API")

    public Result<List<Plant>> getAllPlants() {
        return plantService.getAllPlants();
    }

    @RequestMapping(value = "/img/{id}", method = RequestMethod.GET, produces = {MediaType.IMAGE_PNG_VALUE})
    @ApiOperation(value = "获取植物图片", notes = "获取植物图片 API")
    @ApiImplicitParam(name = "id", value = "植物 id", dataTypeClass = Integer.class, required = true, example = "1")

    public ResponseEntity<byte[]> getPlantImgById(@PathVariable String id) {
        byte[] res = plantService.getImgByPlantId(id);
        if (res == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
        return ResponseEntity.ok(res);
    }
}
